package com.fnd.servicechat.ws;

import com.fnd.servicechat.ws.handler.ChatWebSocketHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.stream.ChunkedWriteHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @Description 定义Initializer
 * @Author Administrator
 * @Date 2019/11/13 12:24
 * @Version 1.0
 */
@Component
public class NettyWebSocketChannelInitializer extends ChannelInitializer<SocketChannel> {

    @Autowired
    private ChatWebSocketHandler chatWebSocketHandler;

    @Override
    public void initChannel(SocketChannel ch) throws Exception {
        ChannelPipeline pipeline = ch.pipeline();
        //websocket协议本身是基于http协议的，所以这边也要使用http解编码器
        pipeline.addLast("http-codec", new HttpServerCodec());
        //netty是基于分段请求的，HttpObjectAggregator的作用是将请求分段再聚合,参数是聚合字节的最大长度
        pipeline.addLast("aggregator", new HttpObjectAggregator(65536));
        //以块的方式来写的处理器
        pipeline.addLast("http-chunked",new ChunkedWriteHandler());
        //参数指的是contex_path
        pipeline.addLast(new WebSocketServerProtocolHandler("/chat"));
        //websocket定义了传递数据的6中frame类型
        pipeline.addLast(chatWebSocketHandler);   //这里不能使用new，不然在handler中不能注入依赖
    }
}
